/**
 * @author mmbro
 * @homepage https://gitee.com/mmbro/
 * @date 2021年05月18日11:34:08
 * @description 注释: rest服务调用工具类
 */
class RestUtil{

    /**
     * @description get请求
     * @param url 请求地址
     * @returns {Promise<Response>}
     */
    static get(url) {
        console.debug('get url: %s', url);
        return fetch(url);
    }

    /**
     * @description post json请求
     * @param url 请求地址
     * @param body 请求内容
     * @param data 请求配置信息(可选)
     * @returns {Promise<Response>}
     */
    static postJson(url, body = {}, data = {}) {
        console.debug('postJson url: %s, param: %o', url, data);
        // 强制指定方法
        Object.assign(data, {method: 'post', mode: 'cors'});
        // 强制指定内容类型
        let {headers = {}} = data;
        Object.assign(headers, {'content-type': 'application/json'});
        let bodyStr = JSON.stringify(body);
        Object.assign(data, {body: bodyStr})
        return fetch(url, data);
    }

    /**
     * @description 原生fetch,自定义请求
     * @param url
     * @param data
     * @returns {Promise<Response>}
     */
    static fetch(url, data) {
        console.debug('fetch url: %s, param: %o', url, data);
        return fetch(url, data);
    }

    test(urls = {}) {
        let defaultUrls = {
            getUrl: '//e.7mo.org:18000/url?url=https://www.baidu.com/img/flexible/logo/pc/result.png',
            postUrl: '//e.7mo.org:18000/admin',
            fetchUrl: '//e.7mo.org:18000/admin',
            fetchParam: {method: 'post'}
        };
        Object.assign(defaultUrls, urls);
        let {getUrl, postUrl, fetchUrl, fetchParam} = defaultUrls;
        //get

        RestUtil.get(getUrl).then(resp => console.log("test get:", resp));
        RestUtil.postJson(postUrl).then(resp => console.log("test postJson:", resp));
        RestUtil.fetch(fetchUrl, fetchParam).then(resp => console.log("test fetch:", resp));
    }

}